<?php

/**
 * Class to handle gallery
 */

class Gallery {

  // Properties

  /**
  * @var int The gallery  ID from the database
  */
  public $id = null;


  /**
  *  @var string the title of the gallery
  */
  public $title = null;


  /**
  * Sets the object's properties using the values in the supplied array
  *
  * @param assoc The property values
  */

  public function __construct( $data=array() ) {
    if ( isset( $data['id'] ) ) $this->id = (int) $data['id'];
    if ( isset( $data['title'] ) ) $this->title = $data['title'];
  }


  /**
  * Sets the object's properties using the edit form post values in the supplied array
  *
  * @param assoc The form post values
  */

  public function storeFormValues ( $params ) {

    // Store all the parameters
    $this->__construct( $params );
  }


  /**
  * Returns an gallery object matching the given gallery ID
  *
  * @param int The gallery ID
  * @return gallery|false The gallery object, or false if the record was not found or there was a problem
  */

  public static function getById( $id ) {
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "SELECT * FROM gallery WHERE id = :id";
    $st = $conn->prepare( $sql );
    $st->bindValue( ":id", $id, PDO::PARAM_INT );
    $st->execute();
    $row = $st->fetch();
    $conn = null;
    if ( $row ) return new Gallery( $row );
  }

  /**
  * Returns all (or a range of) gallery objects in the DB
  *
  * @param int Optional The number of rows to return (default=all)
  * @param string Optional column by which to order the gallery (default="publicationDate DESC")
  * @return Array|false A two-element array : results => array, a list of gallery objects; totalRows => Total number of gallery
  */

  public static function getList( $numRows=1000000) {
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM gallery
            LIMIT :numRows";

    $st = $conn->prepare( $sql );
    $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
    $st->execute();
    $list = array();

    while ( $row = $st->fetch() ) {
      $gallery = new Gallery( $row );
      $list[] = $gallery;
    }

    // Now get the total number of gallery that matched the criteria
    $sql = "SELECT FOUND_ROWS() AS totalRows";
    $totalRows = $conn->query( $sql )->fetch();
    $conn = null;
    return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
  }

  public function getImages( $numRows=1000000) {
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "SELECT * FROM gallery_images WHERE galleryId = :galleryId
            LIMIT :numRows";

    $st = $conn->prepare( $sql );
    $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
    $st->bindValue( ":galleryId", $this->id, PDO::PARAM_INT );
    $st->execute();
    $list = array();

    while( $image =$st->fetch() ) {
      $list[] = $image;
    }

    $conn = null;
    return ( array ( "results" => $list ) );
  }

 public function getImageById( $id ) {
     $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
 	$sql = "SELECT * FROM gallery_images WHERE galleryId = :galleryId AND id = :id";

 	$st = $conn->prepare( $sql );
 	$st->bindValue( ":galleryId", $this->id, PDO::PARAM_INT );
 	$st->bindValue( ":id", $id, PDO::PARAM_INT );
 	$st->execute();
 	$list = array();

 	$image =$st->fetch();
 	$conn = null;

     return $image;
  }

  /**
  * Inserts the current gallery object into the database, and sets its ID property.
  */

  public function insert() {

    // Does the gallery object already have an ID?
    if ( !is_null( $this->id ) ) trigger_error ( "gallery::insert(): Attempt to insert an gallery object that already has its ID property set (to $this->id).", E_USER_ERROR );

    // Insert the gallery
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $this->id = $conn->lastInsertId();
    $sql = "INSERT INTO gallery ( id, title ) VALUES ( :id, :title )";
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":id", $this->id, PDO::PARAM_INT );
    $st->bindValue( ":title", $this->title, PDO::PARAM_STR );
    $st->execute();
    $conn = null;
  }

  public function insertImage( $url ) {

    // Is the url variable set ?
    if ( is_null( $url) ) trigger_error ( "gallery::insertImage(): Attempt to insert a null image url", E_USER_ERROR );

    // Insert the image
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "INSERT INTO gallery_images ( id, image, galleryId ) VALUES ( :id, :image, :galleryId )";
    $st = $conn->prepare( $sql );
    $st->bindValue( ":id", $conn->lastInsertId(), PDO::PARAM_INT );
    $st->bindValue( ":image", $url, PDO::PARAM_STR );
    $st->bindValue( ":galleryId", $this->id, PDO::PARAM_INT );
    $st->execute();
    $conn = null;
  }


  /**
  * Updates the current gallery object in the database.
  */

  public function update() {

    // Does the gallery object have an ID?
    if ( is_null( $this->id ) ) trigger_error ( "gallery::update(): Attempt to update an gallery object that does not have its ID property set.", E_USER_ERROR );

    // Update the gallery
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "UPDATE gallery SET title=:title WHERE id = :id";
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":title", $this->title, PDO::PARAM_STR );
    $st->bindValue( ":id", $this->id, PDO::PARAM_INT );
    $st->execute();
    $conn = null;
  }


  /**
  * Deletes the current gallery object from the database.
  */

  public function delete() {

    // Does the gallery object have an ID?
    if ( is_null( $this->id ) ) trigger_error ( "gallery::delete(): Attempt to delete an gallery object that does not have its ID property set.", E_USER_ERROR );

    // Delete the images relating to the gallery
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $list = array();
    $list = $this->getImages();
    foreach( $list['results'] as $image ) {

    if(unlink( $image['image'] ) ) {
      $st = $conn->prepare ( "DELETE FROM gallery_photos WHERE url = :url" );
      $st->bindValue( ":url", $image['image'], PDO::PARAM_STR );
      $st->execute();
    } else {
      trigger_error ( "gallery::delete(): Attempt to delete an image failed: " . $image['image'], E_USER_ERROR );
    }
  }

    // Delete the gallery
    $st = $conn->prepare ( "DELETE FROM gallery WHERE id = :id LIMIT 1" );
    $st->bindValue( ":id", $this->id, PDO::PARAM_INT );
    $st->execute();
    $conn = null;
  }

  public function deleteImage( $id ) {

    // Does the url exist ?
    if ( is_null( $id ) ) trigger_error ( "gallery::deleteImage(): Attemp to delete an image from a null id.", E_USER_ERROR );

	$image = $this->getImageById( $id );

	if( unlink( $image['image'] ) ) {
      // Delete the image
      $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
      $st = $conn->prepare ( "DELETE FROM gallery_images WHERE id = :id AND galleryId = :galleryId LIMIT 1" );
      $st->bindValue( ":id", $id, PDO::PARAM_STR );
      $st->bindValue( ":galleryId", $this->id, PDO::PARAM_INT );
      $st->execute();
      $conn = null;
    }
  }
}

?>
